package com.itcast.tanhuaserver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.tanhua.dubbo.server.api.QuanZiApi;
import com.itcast.tanhua.dubbo.server.api.VisitorsApi;
import com.itcast.tanhua.dubbo.server.domain.Movements;
import com.itcast.tanhua.dubbo.server.domain.Publish;
import com.itcast.tanhua.dubbo.server.domain.Visitors;
import com.itcast.tanhua.dubbo.server.vo.PageInfo;
import com.itcast.tanhuaserver.domain.User;
import com.itcast.tanhuaserver.domain.UserInfo;
import com.itcast.tanhuaserver.domain.UserThreadLocal;
import com.itcast.tanhuaserver.handle.PicUploadHandle;
import com.itcast.tanhuaserver.service.MovementsService;
import com.itcast.tanhuaserver.service.UserInfoService;
import com.itcast.tanhuaserver.service.UserService;
import com.itcast.tanhuaserver.utils.RelativeDateFormat;
import com.itcast.tanhuaserver.vo.PageResult;
import com.itcast.tanhuaserver.vo.PicUploadResult;
import com.itcast.tanhuaserver.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @PachageName: com.itcast.tanhuaserver.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/1716:15
 * @Version 1.0
 */
@Service
public class MovementsServiceImpl implements MovementsService {
    @Autowired
    private UserService userService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadHandle picUploadHandle;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    /**
     * 发布动态
     * @param textContent   文字动态
     * @param location 位置
     * @param longitude 经度
     * @param latitude 纬度
     * @param image 图片动态（支持多张图片）
     * @param token 登录状态
     * @return 布尔值(保存是否成功)
     */
    @Override
    public String savePublish(String textContent, String location, String longitude, String latitude, MultipartFile[] image, String token) {
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            return null; //token失效或非法
        }
        //发布对象
        Publish publish = new Publish();
        publish.setUserId(user.getId().longValue());
        publish.setText(textContent);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setLocationName(location);
        publish.setId(ObjectId.get());
        //上传多张图片和保存图片路径
        List<String> list = new ArrayList<>();
        for (MultipartFile file : image) {
            PicUploadResult uploadResult = this.picUploadHandle.upload(file);
            list.add(uploadResult.getName());
        }

        publish.setMedias(list);

        //调用dubbo保存publish
        if (this.quanZiApi.savePublish(publish)) {
            return publish.getId().toHexString();
        }
        return null;
    }

    /**
     * 查询好友动态
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult queryPublishList(Integer page, Integer pageSize,boolean isRecommend) {
        PageResult pageResult = new PageResult();
        //通过登录状态获取User
        User user = UserThreadLocal.get();

        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = null;
        if (isRecommend){       //推荐动态逻辑处理
            String value = this.redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + user.getId());
            if (StringUtils.isNotEmpty(value)){
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length){
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length){
                        endIndex = pids.length - 1;
                    }

                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }
        if (null == pageInfo){
            //判断是否是推荐
            Long userId = isRecommend ? null : user.getId().longValue();
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }
        //查询好友动态
        //PageInfo<Publish> pageInfoPublish = ;
        if (isRecommend){
            user = UserThreadLocal.get(); // 若是推荐给user重新赋值,下面点赞和喜欢 查询redis要用
        }

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //没有好友动态信息
            return pageResult;
        }

        pageResult.setItems(queryMovementsList(records));
        return pageResult;
    }

    private List<Movements> queryMovementsList(List<Publish> records){
        User user = UserThreadLocal.get();
        List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setUserId(record.getUserId());
            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
            movements.setId(record.getId().toHexString());
            movements.setTextContent(record.getText());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));
            movements.setImageContent(record.getMedias().toArray(new String[]{}));

            String redisUserLikekey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLiked(this.redisTemplate.hasKey(redisUserLikekey) ? 1 : 0); // 是否点赞（1是，0否）

            String redisLikeKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
            String likeCountValue = this.redisTemplate.opsForValue().get(redisLikeKey);
            if (StringUtils.isNotEmpty(likeCountValue)){
                movements.setLikeCount(Integer.parseInt(likeCountValue)); // 点赞数
            }else{
                movements.setLikeCount(0); // 点赞数
            }


            String redisUserLovekey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(redisUserLovekey) ? 1 : 0); // 是否喜欢（1是，0否）

            String redisLoveKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveCountValue = this.redisTemplate.opsForValue().get(redisLoveKey);
            if (StringUtils.isNotEmpty(loveCountValue)){
                movements.setLoveCount(Integer.parseInt(loveCountValue)); // 喜欢数
            }else{
                movements.setLoveCount(0); // 喜欢数
            }

            movements.setCommentCount(996); //TODO 评论数
            movements.setDistance("0.1公里"); //TODO 距离

            movementsList.add(movements);
        }

        //movements中添加userInfo信息
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(query);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()){
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    if (userInfo.getSex() == null){
                        movements.setGender("man");
                    }
                    else{
                        movements.setGender(userInfo.getSex().name().toLowerCase());
                    }

                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(),","));
                }
            }
        }

        return movementsList;
    }

    /**
     * 点赞
     * @param publishId
     * @return
     */
    @Override
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean likeComment = this.quanZiApi.saveLikeComment(user.getId().longValue(), publishId);
        if (!likeComment){
            return null;
        }

        //返回的count从redis缓存中获取,redis中没有从mongoDB中查询加到redis中
        Long count = 0L;
        String redisLikeKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!this.redisTemplate.hasKey(redisLikeKey)){
            Long commentCount = this.quanZiApi.queryCommentCount(publishId, 1);
            this.redisTemplate.opsForValue().set(redisLikeKey,String.valueOf(commentCount));
            count = commentCount;
        }
        else{
            //点赞递增
            count = this.redisTemplate.opsForValue().increment(redisLikeKey);
        }

        //标记user已经点赞
        String redisUserLikekey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(redisUserLikekey,"1");
        return count;
    }

    @Override
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean loveComment = this.quanZiApi.saveLoveComment(user.getId().longValue(), publishId);
        if (!loveComment){
            return null;
        }

        //返回的count从redis缓存中获取,redis中没有从mongoDB中查询加到redis中
        Long count = 0L;
        String redisLoveKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(redisLoveKey)){
            Long commentCount = this.quanZiApi.queryCommentCount(publishId, 3);
            this.redisTemplate.opsForValue().set(redisLoveKey,String.valueOf(commentCount));
            count = commentCount;
        }
        else{
            //喜欢递增
            count = this.redisTemplate.opsForValue().increment(redisLoveKey);
        }

        //标记user已经喜欢
        String redisUserLovekey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(redisUserLovekey,"1");
        return count;
    }

    @Override
    public Long unloveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean loveComment = this.quanZiApi.removeComment(user.getId().longValue(), publishId,3);
        if (loveComment){
            //喜欢数量递减
            String redisLoveKey = "QUANZI_COMMENT_LOVE_" + publishId;
            Long decrement = this.redisTemplate.opsForValue().decrement(redisLoveKey);

            //删除user已喜欢
            String redisUserLovekey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(redisUserLovekey);
            return decrement;
        }
        return null;
    }


    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    @Override
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean likeComment = this.quanZiApi.removeComment(user.getId().longValue(), publishId,1);
        if (likeComment){
            //点赞数量递减
            String redisLikeKey = "QUANZI_COMMENT_LIKE_" + publishId;
            Long decrement = this.redisTemplate.opsForValue().decrement(redisLikeKey);

            //删除user已点赞
            String redisUserLikekey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(redisUserLikekey);
            return decrement;
        }
        return null;
    }

    /**
     * 查询单条动态
     * @param publishId
     * @return
     */
    @Override
    public Movements queryMovementsById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null){
            return null;
        }

        List<Movements> movementsList = queryMovementsList(Arrays.asList(publish));
        return movementsList.get(0);
    }

    @Override
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_" + user.getId();
        String value = this.redisTemplate.opsForValue().get(redisKey);
        List<Visitors> visitorsList = null;
        if (StringUtils.isNotEmpty(value)){
            visitorsList = this.visitorsApi.topVisitor(user.getId().longValue(), Long.valueOf(value));
        }
        else{
            visitorsList = this.visitorsApi.topVisitor(user.getId().longValue(),5);
        }

        if (CollectionUtils.isEmpty(visitorsList)){
            return Collections.emptyList();
        }

        List<Long> userIds = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            if (!userIds.contains(visitors.getUserId())){
                userIds.add(visitors.getUserId());
            }
        }

        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(query);
        List<VisitorsVo> visitorList = new ArrayList<>();

        for (Visitors visitors : visitorsList) {
            for (UserInfo userInfo : userInfos) {
                if (visitors.getUserId().longValue() == userInfo.getUserId().longValue()){
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex() == null ? "man" : userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(),","));
                    visitorsVo.setFateValue(visitors.getScore().intValue());
                    visitorList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorList;
    }

    @Override
    public PageResult queryAlbumList(Integer page, Integer pageSize, Long userId) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        List<Movements> movementsList = this.queryMovementsList(records);
        pageResult.setItems(movementsList);
        /*List<Movements> movementsList = new ArrayList<>();
        List<Long> userIds = new ArrayList<>();
        for (Publish record : records) {
            Movements movement = new Movements();
            movement.setUserId(record.getUserId());
            movement.setId(record.getId().toHexString());
            movement.setTextContent(record.getText());
            movement.setImageContent(record.getMedias().toArray(new String[]{}));
            movement.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
            movementsList.add(movement);
        }

        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(query);

        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()){

                    break;
                }
            }
        }*/


        return pageResult;
    }


}
